<template>

  <div class="AddOrUpdate_main add_container main_container">

    <div class="main_main">
      <div class="share_container ">
        <div class="left">
          <div class="share_titile">引荐好友，领取极分</div>
          <div class="share_tip">把引荐链接发给好友，对方注册账号并完成企业认证通过后，有机会获得 88 极分</div>
          <div class="share">
            <div class="share_url">
              <div class="url">引荐链接：{{ encryptUrl }}</div>
            </div>
            <el-button @click="copyUrl">复制链接</el-button>
          </div>
        </div>
        <div class="code">
          <canvas id="QRCode_header" />
          <el-button type="text" @click="downloadCode">点击下载</el-button>
        </div>
      </div>
      <div class="share_container">
        <div class="left">
          <div class="share_titile">分享海报，领取极分</div>
          <div class="share_tip">制作引荐海报分享，对方注册账号并完成企业认证通过后，有机会获得 88 极分</div>
          <div class="share">
            <div class="share_url">
              <div class="url">海报制作链接：{{ shareUrl }}</div>
            </div>
            <el-button @click="doUrl">去制作</el-button>
          </div>
        </div>
        <div v-if="$store.state.user.poster&&$store.state.user.poster.pictureUrl" class="code">
          <el-image
            class="img"
            :src="$store.state.user.poster.pictureUrl"
            :preview-src-list="[$store.state.user.poster.pictureUrl]"
          />
          <!-- <img :src="$store.state.user.poster.pictureUrl" alt="" @click="previewPicture"> -->
          <!-- <canvas id="QRCode_header2" /> -->
          <el-button type="text" @click="downloadShare">点击下载</el-button>
        </div>
      </div>
      <div class="formItem_header">引荐记录</div>
      <SlideTable ref="SlideTable" :no-more="noMore" :table-data="tableData" :table-column="tableColumn" @loadMoreData="loadMoreData" />
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode'
import { list } from '@/api/common/personalCenter'
import { mapGetters } from 'vuex'
import CryptoJS from 'crypto-js'
import defaultSettings from '@/settings'
import SlideTable from './SlideTable.vue'
export default {
  name: 'PersonalAccount',
  components: {
    SlideTable
  },
  computed: {
    ...mapGetters([
      'userId', 'userName', 'companyId', 'avatar'
    ])
  },
  data() {
    return {
      showPreview: false,
      tableData: [],
      pageData: {
        pageNum: 1,
        pageSize: 5
      },
      shareCode: '',
      tableColumn: [
        { label: '注册企业', prop: 'companyName', minWidth: '200' },
        { label: '注册人名称', prop: 'registerName' },
        { label: '注册人手机号', prop: 'registerPhone' },
        { label: '注册时间', prop: 'registerTime' },
        { label: '企业认证', prop: 'authStatusName' },
        { label: '认证时间', prop: 'authTime' }
      ],
      noMore: false,
      formData: {
        userId: undefined,
        realName: undefined,
        email: undefined,
        deptName: undefined,
        deptId: undefined,
        expirationTime: '',
        userName: ''
      },
      encryptUrl: '',
      shareUrl: 'https://sharePoster.cascadeiot.com',
      isAdmin: false,
      edit1: false,
      edit2: false,
      rules: {
        name: [
          { required: true, message: '公司名称不能为空', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    const json = {
      referralUserId: this.$store.state.user.userId,
      referralUserType: '2'
    }
    const key = this.encrypt(JSON.stringify(json), defaultSettings.aesKey)
    this.encryptUrl = window.location.host + '/#/login?key=' + key
    this.getList()
    this.$nextTick(() => {
      this.getQRCode()
      // this.getQRCode2()
    })
  },
  methods: {
    downloadShare() {
      var image = new Image()
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous')
      image.onload = function() {
        var canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height

        var context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        var url = canvas.toDataURL('image/png')
        var a = document.createElement('a')
        // 创建一个单击事件
        var event = new MouseEvent('click')
        a.download = '海报分享'
        a.href = url

        // 触发a的单击事件
        a.dispatchEvent(event)
      }
      image.src = this.$store.state.user.poster.pictureUrl
    },
    downloadCode() {
      // 获取canvas标签
      const canvas = document.getElementById('app').getElementsByTagName('canvas')
      // 创建a标签
      const a = document.createElement('a')
      // 解决跨域 Canvas 污染问题
      a.setAttribute('crossOrigin', 'anonymous')
      // 获取二维码的url并赋值为a.href
      a.href = canvas[0].toDataURL('img/png')
      // 设置下载文件的名字
      a.download = '邀请码'
      // 点击事件，相当于下载
      a.click()
      // 清空下载地址
      this.shareCode = ''
    },
    getQRCode() {
      const json = {
        referralUserId: this.$store.state.user.userId,
        referralUserType: '2'
      }
      const key = this.encrypt(JSON.stringify(json), defaultSettings.aesKey)
      this.shareCode = 'https://miniprogram.cascadeiot.com/miniprogram/register?key=' + key
      // 生成的二维码为URL地址js
      const opts = {
        errorCorrectionLevel: 'H', // 容错级别
        type: 'image/png', // 生成的二维码类型
        quality: 0.3, // 二维码质量
        margin: 0, // 二维码留白边距
        width: 100, // 宽
        height: 100, // 高
        text: this.shareCode, // 二维码内容
        color: {
          dark: '#333333', // 前景色
          light: '#fff' // 背景色
        }
      }

      const msg = document.getElementById('QRCode_header')
      // 将获取到的数据（val）画到msg（canvas）上
      QRCode.toCanvas(msg, this.shareCode, opts, function(error) {
        if (error) {
          console.log('二维码加载失败', error)
          this.$message.error('二维码加载失败')
        }
      })
    },
    getQRCode2() {
    // 生成的二维码为URL地址js
      const opts = {
        errorCorrectionLevel: 'H', // 容错级别
        type: 'image/png', // 生成的二维码类型
        quality: 0.3, // 二维码质量
        margin: 0, // 二维码留白边距
        width: 100, // 宽
        height: 100, // 高
        text: this.encryptUrl, // 二维码内容
        color: {
          dark: '#333333', // 前景色
          light: '#fff' // 背景色
        }
      }

      const msg = document.getElementById('QRCode_header2')
      // 将获取到的数据（val）画到msg（canvas）上
      QRCode.toCanvas(msg, this.encryptUrl, opts, function(error) {
        if (error) {
          console.log('二维码加载失败', error)
          this.$message.error('二维码加载失败')
        }
      })
    },
    loadMoreData() {
      this.pageData.pageNum++
      this.getList()
    },
    getList() {
      list({ userId: this.$store.state.user.userId, ...this.pageData }).then(res => {
        if (res.data.length < this.pageData.pageSize) {
          this.noMore = true
        }
        this.tableData = this.tableData.concat(res.data)
        setTimeout(() => {
          this.$refs.SlideTable.stopLoad()
        }, 200)
      })
    },
    doUrl() {
      // const routerUrl = this.$router.resolve({ path: '/largeScreen', query: { code: row.code }})
      window.open(this.shareUrl, '_blank')
      // this.$router.push('/iframe')
    },
    // aes加密
    encrypt(word, keyStr) {
      keyStr = keyStr || 'absoietlj32fai12'
      const key = CryptoJS.enc.Utf8.parse(keyStr)
      const srcs = CryptoJS.enc.Utf8.parse(word)
      const encrypted = CryptoJS.AES.encrypt(srcs, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      })
      return encrypted.toString()
      // aes加密后，拼接到URL
      // const key = this.encrypt(JSON.stringify(json), defaultSettings.aesKey)
      // ele.addr = window.location.host + '/#/largeScreen?key=' + key
    },

    copyUrl() {
      // navigator.clipboard.writeText(this.encryptUrl)
      // this.$message.success('复制成功')

      if (navigator.clipboard && window.isSecureContext) {
        // navigator clipboard 向剪贴板写文本
        navigator.clipboard.writeText(this.encryptUrl)
        this.$message.success('复制成功')
      } else {
        // 创建text area
        const textArea = document.createElement('textarea')
        textArea.value = this.encryptUrl
        // 使text area不在viewport，同时设置不可见
        textArea.style.position = 'absolute'
        textArea.style.opacity = 0
        textArea.style.left = '-999999px'
        textArea.style.top = '-999999px'
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        return new Promise((res, rej) => {
          // 执行复制命令并移除文本框
          document.execCommand('copy') ? res() : rej()
          textArea.remove()
          this.$message.success('复制成功')
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-image__inner{
  width: unset !important;
}
.main_container{
  height: 100%;
}
.main_main{
height: 100%;
overflow: auto;
margin: unset !important;
padding: 0 20px;
}
.share_container{
   margin-top: 10px;

  padding:20px 0px 5px 20px;
  background-color: rgb(249, 249, 249);
  border-radius: 8px;
  display: flex;
  // align-items: center;
  // justify-content: space-between;
  .left{
    width: calc(100% - 190px);
    // width: calc(90% - 150px);
  }
  .code{
    // margin-left: 20px;
    width:190px ;
    // margin-left: 10%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .img{
      object-fit: contain;
      // width: 100px;
      // text-align: center;
      height: 100px;
    }
  }
  .share_titile{
    font-size: 14px;
  }
  .share_tip{
    font-size: 14px;
    color: #999;
    margin: 20px 0;
  }
  .share{
    display: flex;
    align-items: center;
    .share_url{
      padding: 5px 16px;
      background-color: rgb(242,243,243);
      font-size: 14px;
      border-radius:8px ;
      margin-right: 20px;
      width: calc(100% - 100px);
      .url{
        // width:;
        overflow:hidden;
        text-overflow: ellipsis;
        white-space:nowrap;
      }
    }
    /deep/ .el-button{
      background-color: #387BFC;
      // font-size: 14px;
      font-weight: 600;
      width: 80px;
      // height: 30px;
      // line-height: 30px;
    }
  }
}
.image{
  margin-top: 20px;
  height: 180px;
  width: 180px;
  padding-left: 10px;
  img{
    height: 100%;
    width: 100%;
  }
}
.title{
  font-size: 30px;
  color: rgb(0, 118, 224);
}
.avatar_title{
  color: #999;
  padding-left: 10px !important;
  span{
    color: rgb(0, 118, 224);
    margin-left: 10px;
    cursor: pointer;
  }
}
.tip{
  color: #999;
}
.formItem_header{
  font-weight: bold;
  // font-weight: 500;
  margin-top: 40px;
  // font-size: 24px !important;
  padding-left: 0px !important;

}
.share_magrin{
  margin-top: 20px;
}
.main_main{
  padding-top: 5px !important;
  // margin: 0;
  // padding-left: 20px;
  .personalCenter_div{
    width: 100%;height: 90px;
    display: flex;align-items: center;
    .avatar_div_container{
      width: 66px;
      height: 66px;
      border-radius: 50%;
      margin-right: 40px;
      margin-left: 10px;
      display: flex;justify-content: flex-start;align-items: center;
    }
    .avatar_div{
      height: 100%;
      width: 100%;

      position: relative;
      img{
        width: 66px;height: 66px;
        border-radius: 50%;
      }
      .avatar_button{
        position: absolute;
        top: 0;left: 0;
        width: 66px;height: 66px;
        border-radius: 50%;
        justify-content: center;align-items: center;
        font-size: 22px;
        background-color: #3333334d;
        display: none;
        color: white;
      }
    }
    .avatar_div:hover{
      .avatar_button{
        display: flex;
      }
    }
    .name_div{
      height: 100%;
      display: flex;justify-content: center;
      flex-direction: column;
      .name_div_name{
        font-size: 22px;
        height: 40px;line-height: 40px;
      }
      .name_div_company{
        font-size: 16px;
        color: #666666;
        height: 40px;line-height: 40px;
      }
    }
  }

  .accountInfo_div{
    margin: 20px 20px 0;
    .accountInfo_item{
      display: flex;align-items: center;
      .accountInfo_item_name{
        width: 150px;
        height: 40px;
        font-size: 18px;
        font-weight: 400;
        color: #666;
      }
      .accountInfo_item_value{

        height: 40px;
        width: 150px;
            text-align: right;
        .value_show{
          display: flex;align-items: center;justify-content: space-between;
          .value_show_name{
            height: 100%;
            display: flex;align-items: center;
          }
          .value_show_edit{
            height: 100%;
            display: flex;align-items: center;
            margin-left: 20px;
            font-size: 18px;
          }
        }

          .value_show_operate{
            width: 100%;text-align:right;
            color: #387bfc;
          }

        .value_edit{
          width: 100%;
          /deep/ .el-input__inner{
            height: 30px;
          }
        }
      }
    }
  }
}

</style>
